package com.chenshu.shop.controller.index;

import com.chenshu.shop.common.Constant;
import com.chenshu.shop.common.PageUtil;
import com.chenshu.shop.common.SessionUtil;
import com.chenshu.shop.model.Item;
import com.chenshu.shop.model.Order;
import com.chenshu.shop.model.User;
import com.chenshu.shop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-18
 * Time：11:26
 */
@RequestMapping("/index")
@Controller
public class OrderController_index {
    @Autowired
    OrderService orderService;
    @RequestMapping("/orderSave")
    public String orderSave(HttpServletRequest request) {
        User user = SessionUtil.getLoginUser(request);
        assert user != null;
        //生成订单
        Integer orderId = orderService.addOrder(user.getId());
        //获取订单信息
        Order order = orderService.getOrderById(orderId);

        request.setAttribute("order", order);
        HttpSession session = request.getSession(false);
        session.setAttribute(Constant.USER_CART_COUNT, 0);
        return "forward:/index/pay.jsp";
    }

    @RequestMapping("order")
    public String order(HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "1") int page,
                        @RequestParam(required = false, defaultValue = "3") int size){

        User user = (User) request.getSession().getAttribute(Constant.SESSION_USER_INFO_KEY);
        List<Order> orderList = orderService.getAllOrdersById(user.getId(),page,size);

        request.setAttribute("orderList",orderList);
        Integer count =orderService.getCountsByUserId(user.getId());
        String pageHtml = PageUtil.getPageHtml(request, count, page, size);
        request.setAttribute("pageHtml",pageHtml);
        return "forward:/index/order.jsp";
    }

    @RequestMapping("/orderPay")
    public String orderPay(Order order) {
        orderService.updateOrder(order);
        return "redirect:/index/payok.jsp";
    }

    @RequestMapping("/orderJump")
    public String orderJump(HttpServletRequest request, Integer id) {
        Order order = orderService.getOrderById(id);
        request.setAttribute("order", order);
        return "forward:/index/pay.jsp";
    }
}
